'use strict';
var timer = null
Object.defineProperty(exports, "__esModule", {
  value: true
});

//语音识别
var recorder;
var file;
var that;

exports.default = Page({
  data: {
    scroll: "",

    days: 0,
    tab: 1,
    step: -1,
    input: '',
    btn_disabled: false,
    records: [],
    scroll_bottom: "_0",
    visible2: false,
    j: 1, //帧动画初始图片

    //语音识别
    serectkey: '4IaeejHd9c2elnfVIqin01kDWaI6f4KU',

    secret_id: 'AKIDiEYoqd1blgVBbml1mPmyvOntPjqWlcR7',

    token: "",

    recording: false,

    cancel_record: false,

    start_y: '',

    fileBase64: '', //base64的文件

    rate: 8000,

    filePath: '', //录音文件

    fileLen: 0, //录音长度

    result: "",

    button: 0,

  },

  copy: function(e) {
    var self = this;
    wx.setClipboardData({
      data: "OursparkMinelab",
      success: function(res) {}
    });
  },

  //语音识别

  submit() {

    let serectkey = that.data.serectkey;

    let param = {

      Action: 'SentenceRecognition',

      Version: '2018-05-22',

      ProjectId: '0', //腾讯云项目ID

      SubServiceType: 2, //一句话识别，没得选

      EngSerViceType: '8k', //引擎类型 8k（电话） 或 16k

      SourceType: 1, //0为url 1为数据

      VoiceFormat: 'mp3', //格式 MP3 或 wav

      UsrAudioKey: new Date().getTime(), //唯一识别,可以直接用时间戳

      Data: that.data.fileBase64,

      DataLen: base64_decode(that.data.fileBase64).length, //未进行base64编码时的数据长度

      Timestamp: parseInt(new Date().getTime() / 1000),

      Nonce: parseInt(new Date().getTime() / 1000),

      SecretId: that.data.secret_id,

    };

    //把参数按键值大小排序并拼接成字符串

    let data = ksort(param);

    let arr = [];

    for (var x in data) {

      data[x] = encodeURI(data[x]);

      arr.push(x + '=' + data[x]);

    }

    let str = arr.join('&');

    //签名生成

    let sign = 'POSTaai.tencentcloudapi.com/?' + str;

    sign = b64_hmac_sha1(serectkey, sign);

    data['Signature'] = sign;

    //友好的提示

    wx.showLoading({

      title: '发送中...',

    })

    console.log("签名发送中")

    wx.request({

      url: 'https://aai.tencentcloudapi.com/',

      data: data,

      header: {

        'content-type': 'application/x-www-form-urlencoded'

      },

      method: 'post',

      success: function(e) {

        console.log(e.data)


        that.setData({

          input: e.data.Response.Result.replace("\u3002", "")

        })


      },

      complete() {
        wx.hideLoading();
      }

    })

  },

  //手指按下

  clickDown(e) {
    var _this = this;
    //话筒帧动画
    var i = 0;
    timer = setInterval(function() {
      i++;
      i = i % 5;
      _this.setData({
        j: i
      })
      return
    }, 200);

    recorder.onStart(() => {

      console.log('recorder start')

      wx.showToast({

        title: "录音中",

        icon: "none",

      });

    });

    //开始录音

    recorder.start({

      duration: 60000, //最大时长

      sampleRate: that.data.rate, //采样率

      numberOfChannels: 1, //录音通道数

      encodeBitRate: 24000, //编码码率，有效值见下表格

      format: 'mp3', //音频格式

      // frameSize: 2000,//指定大小 kb

    })

  },

  //手指松开

  clickUp(e) {


    //去除帧动画循环
    clearInterval(timer)

    if (timer) {
      clearInterval(timer)
    }

    //停止录音

    recorder.stop();

    recorder.onStop((e) => {
      console.log('end');

      //保存录音文件的临时路径

      that.setData({

        filePath: e.tempFilePath,

      })

      console.log(e.tempFilePath);

      // wx.setStorageSync('filePath', e.tempFilePath);

      //友好的加载

      wx.showLoading({

        title: '文件读取中...'

      })

      console.log("文件读取中")

      //读取录音文件，并转为base64编码

      file.readFile({

        filePath: e.tempFilePath,

        encoding: 'base64',

        success: function(e) {

          that.setData({

            fileBase64: e.data

          })

          console.log(e)

          that.submit()

        },

        complete() {

          wx.hideLoading();

        },

      })

    })

  },

  //检查是否关注公众号
  checkSubscription: function(go) {
    wx.login({
      success(res1) {
        if (res1.code) {
          // console.log(111)
          // 发起网络请求
          wx.request({
            url: 'https://www.ourspark.org/helloworld/checkSubscription',
            data: {
              code: res1.code
            },
            method: "POST",
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            success: function(resin) {
              console.log(resin)
              if (resin.data.error_no == 2) {
                wx.showModal({
                  title: "哎呀~",
                  content: resin.data.error_msg,
                })
              } else if (resin.data.error_no == 1) {
                if (resin.data.doc && resin.data.doc.attention) {
                  go()
                } else {
                  wx.showModal({
                    title: '提示！',
                    content: '请按照说明先关注指定服务号。',
                  })
                }
              }
            },
            fail: function(resin) {

            }
          })
        } else {
          console.log('登录失败！' + res1.errMsg)
        }
      }
    })
  },

  toGroup1: function() {

    let go = () => {
      wx.navigateTo({
        url: '/pages/group-in/group-in?num=1',
      })
    }

    this.checkSubscription(go)
    
  },

  toGroup2: function() {

    let go = () => {
      wx.navigateTo({
        url: '/pages/group-in/group-in?num=2',
      })
    }

    this.checkSubscription(go)
    
  },

  onClose(key) {
    console.log('onClose')
    this.setData({
      [key]: false,
    })
  },
  onClose2() {
    this.onClose('visible2')
  },

  open2() {
    this.setData({
      visible2: true,
    })
  },

  find_step: function(arr) {
    if (arr.length == 0) return 0

    var step = 0
    for (var i = 0; i < arr.length; i++) {
      if (arr[i].step) {
        if (arr[i].step > step) {
          step = arr[i].step
        }
      }
    }

    return step
  },

  onShow() {
    wx.login({
      success(res1) {
        if (res1.code) {
          // console.log(111)
          // 发起网络请求
          wx.request({
            url: 'https://www.ourspark.org/helloworld/query',
            data: {
              code: res1.code
            },
            method: "POST",
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            success: function(resin) {
              console.log(resin)
              if (resin.data.error_no == 2) {
                wx.showModal({
                  title: "哎呀~",
                  content: resin.data.error_msg,
                })
              } else if (resin.data.error_no == 1) {
                let record_list = resin.data.records

                let step = that.find_step(record_list)

                getApp().globalData.step = step
                that.setData({
                  records: resin.data.records,
                  days: resin.data.days,
                  step
                });
              }
            },
            fail: function(resin) {

            }
          })
        } else {
          console.log('登录失败！' + res1.errMsg)
        }
      }
    })
  },

  onLoad(options) {
    that = this;

    if (options.scroll) {
      that.setData({
        tab: parseInt(options.tab),
        scroll: options.scroll
      })
    }

    recorder = wx.getRecorderManager();
    file = wx.getFileSystemManager();

    wx.login({
      success(res1) {
        if (res1.code) {
          // console.log(111)
          // 发起网络请求
          wx.request({
            url: 'https://www.ourspark.org/helloworld/query',
            data: {
              code: res1.code
            },
            method: "POST",
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            success: function(resin) {
              console.log(resin)
              if (resin.data.error_no == 2) {
                wx.showModal({
                  title: "哎呀~",
                  content: resin.data.error_msg,
                })
              } else if (resin.data.error_no == 1) {
                let record_list = resin.data.records

                let step = that.find_step(record_list)

                getApp().globalData.step = step
                that.setData({
                  records: resin.data.records,
                  days: resin.data.days,
                  step
                });
              }
            },
            fail: function(resin) {

            }
          })
        } else {
          console.log('登录失败！' + res1.errMsg)
        }
      }
    })
  },

  delete_record(e) {
    var that = this
    var index = e.currentTarget.dataset.index

    wx.showModal({
      title: '提示',
      content: '确定要删除这条记录吗？',
      success: function success(res) {
        if (res.confirm) {
          console.log('用户点击确定');

          wx.request({
            url: 'https://www.ourspark.org/helloworld/delete',
            data: {
              _id: that.data.records[index]._id
            },
            method: "POST",
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            success: function(res) {
              console.log(res)
              if (res.data.error_no == 2) {
                wx.showModal({
                  title: "哎呀~",
                  content: res.data.error_msg,
                })
              } else if (res.data.error_no == 1) {
                var records_temp = that.data.records
                records_temp.splice(index, 1)
                that.setData({
                  records: records_temp
                });

                wx.showToast({
                  title: '成功',
                  icon: 'success',
                  duration: 1000
                });

              }
            },
            fail: function(res) {

            }
          })

        } else if (res.cancel) {
          console.log('用户点击取消');
        }
      }
    });
  },

  toBook(e) {
    let step = parseInt(e.currentTarget.dataset.step)
    if (step <= this.data.step + 1 || step == 1) {
      var url = ''

      switch (step) {
        case 1:
          url = '../miniProgram/miniProgram'
          break;
        case 2:
          url = '../miniProgram2/miniProgram2'
          break;
        case 3:
          url = '../miniProgram3/miniProgram3'
          break;
        case 4:
          url = '../miniProgram4/miniProgram4'
          break;
        case 5:
          url = '../miniProgram5/miniProgram5'
          break;
        case 6:
          url = '../miniProgram6/miniProgram6'
          break;
        case 7:
          url = '../miniProgram7/miniProgram7'
          break;
        case 8:
          url = '../CloudFunction/CloudFunction'
          break;
        case 9:
          url = '../CloudFunction2/CloudFunction2'
          break;
        case 10:
          url = '../CloudFunction3/CloudFunction3'
          break;
        case 11:
          url = '../CloudFunction4/CloudFunction4'
          break;
        case 12:
          url = '../CloudFunction5/CloudFunction5'
          break;
        case 13:
          url = '../database/database'
          break;
        case 14:
          url = '../database1/database1'
          break;
        case 15:
          url = '../CloudFunction6/CloudFunction6'
          break;
        case 16:
          url = '../miniProgram8/miniProgram8'
          break;
        default:
          break
      }

      wx.navigateTo({
        url: url,
      })
    } else {
      wx.showModal({
        title: '提示~',
        content: '您还没有完成前面的步骤呦！',
      })
    }

  },

  toDesign(e) {
    let step = e.currentTarget.dataset.step

    wx.navigateTo({
      url: "../design1/design1?step=" + step
    })


  },
  onClick() {
    const current = this.data.current + 1 > 2 ? 0 : this.data.current + 1

    this.setData({
      current,
    })
  },
  selectOne: function selectOne() {
    this.setData({
      tab: 1
    });
  },
  selectTwo: function selectTwo() {
    this.setData({
      tab: 2
    });
  },
  selectThree: function selectThree() {
    this.setData({
      tab: 3
    });
  },

  selectFour: function selectFour() {
    this.setData({
      tab: 4
    });
  },
  formSubmit: function formSubmit(e) {
    var that = this
    if (e.detail.value.input_content == '') {
      wx.showModal({
        title: '提示',
        content: '输入不能为空',
        success: function success(res) {
          if (res.confirm) {
            console.log('用户点击确定');
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        }
      });

      return;
    }
    this.setData({
      btn_disabled: true
    });

    wx.showLoading({
      title: '上传中'
    });

    wx.login({
      success(resout) {
        if (resout.code) {
          console.log(111)
          // 发起网络请求
          wx.request({
            url: 'https://www.ourspark.org/helloworld/add',
            data: {
              code: resout.code,
              content: e.detail.value.input_content
            },
            method: "POST",
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            success: function(res) {
              console.log(res)
              if (res.data.error_no == 2) {
                wx.showModal({
                  title: "哎呀~",
                  content: res.data.error_msg,
                })
              } else if (res.data.error_no == 1) {
                wx.hideLoading();

                wx.showToast({
                  title: '成功',
                  icon: 'success',
                  duration: 1000
                });

                that.setData({
                  input: '',
                  btn_disabled: false
                });

                wx.login({
                  success(res1) {
                    if (res1.code) {
                      // console.log(111)
                      // 发起网络请求
                      wx.request({
                        url: 'https://www.ourspark.org/helloworld/query',
                        data: {
                          code: res1.code
                        },
                        method: "POST",
                        header: {
                          "Content-Type": "application/x-www-form-urlencoded"
                        },
                        success: function(resin) {
                          console.log(resin)
                          if (resin.data.error_no == 2) {
                            wx.showModal({
                              title: "哎呀~",
                              content: resin.data.error_msg,
                            })
                          } else if (resin.data.error_no == 1) {
                            let record_list = resin.data.records
                            let step = that.find_step(record_list)

                            getApp().globalData.step = step
                            that.setData({
                              records: resin.data.records,
                              scroll_bottom: "_" + (resin.data.records.length - 1),
                              days: resin.data.days,
                              step
                            });
                          }
                        },
                        fail: function(resin) {

                        }
                      })
                    } else {
                      console.log('登录失败！' + res1.errMsg)
                    }
                  }
                })
              }
            },
            fail: function(res) {

            }
          })
        } else {
          console.log('登录失败！' + resout.errMsg)
        }
      }
    })
  },
});

//对象按键值排序方法

function ksort(obj) {

  let temp = 'Action';

  let k_arr = [];

  for (var x in obj) {

    k_arr.push(x);

  }

  k_arr.sort();

  let res = {};

  for (let i = 0; i < k_arr.length; i++) {

    let k = k_arr[i];

    res[k] = obj[k];

  }

  return res;

}

//加密函数

function b64_hmac_sha1(k, d, _p, _z) {

  // heavily optimized and compressed version of http://pajhome.org.uk/crypt/md5/sha1.js

  // _p = b64pad, _z = character size; not used here but I left them available just in case

  if (!_p) {
    _p = '=';
  }
  if (!_z) {
    _z = 8;
  }

  function _f(t, b, c, d) {
    if (t < 20) {
      return (b & c) | ((~b) & d);
    }
    if (t < 40) {
      return b ^ c ^ d;
    }
    if (t < 60) {
      return (b & c) | (b & d) | (c & d);
    }
    return b ^ c ^ d;
  }

  function _k(t) {
    return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 : (t < 60) ? -1894007588 : -899497514;
  }

  function _s(x, y) {
    var l = (x & 0xFFFF) + (y & 0xFFFF),
      m = (x >> 16) + (y >> 16) + (l >> 16);
    return (m << 16) | (l & 0xFFFF);
  }

  function _r(n, c) {
    return (n << c) | (n >>> (32 - c));
  }

  function _c(x, l) {
    x[l >> 5] |= 0x80 << (24 - l % 32);
    x[((l + 64 >> 9) << 4) + 15] = l;
    var w = [80],
      a = 1732584193,
      b = -271733879,
      c = -1732584194,
      d = 271733878,
      e = -1009589776;
    for (var i = 0; i < x.length; i += 16) {
      var o = a,
        p = b,
        q = c,
        r = d,
        s = e;
      for (var j = 0; j < 80; j++) {
        if (j < 16) {
          w[j] = x[i + j];
        } else {
          w[j] = _r(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
        }
        var t = _s(_s(_r(a, 5), _f(j, b, c, d)), _s(_s(e, w[j]), _k(j)));
        e = d;
        d = c;
        c = _r(b, 30);
        b = a;
        a = t;
      }
      a = _s(a, o);
      b = _s(b, p);
      c = _s(c, q);
      d = _s(d, r);
      e = _s(e, s);
    }
    return [a, b, c, d, e];
  }

  function _b(s) {
    var b = [],
      m = (1 << _z) - 1;
    for (var i = 0; i < s.length * _z; i += _z) {
      b[i >> 5] |= (s.charCodeAt(i / 8) & m) << (32 - _z - i % 32);
    }
    return b;
  }

  function _h(k, d) {
    var b = _b(k);
    if (b.length > 16) {
      b = _c(b, k.length * _z);
    }
    var p = [16],
      o = [16];
    for (var i = 0; i < 16; i++) {
      p[i] = b[i] ^ 0x36363636;
      o[i] = b[i] ^ 0x5C5C5C5C;
    }
    var h = _c(p.concat(_b(d)), 512 + d.length * _z);
    return _c(o.concat(h), 512 + 160);
  }

  function _n(b) {
    var t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
      s = '';
    for (var i = 0; i < b.length * 4; i += 3) {
      var r = (((b[i >> 2] >> 8 * (3 - i % 4)) & 0xFF) << 16) | (((b[i + 1 >> 2] >> 8 * (3 - (i + 1) % 4)) & 0xFF) << 8) | ((b[i + 2 >> 2] >> 8 * (3 - (i + 2) % 4)) & 0xFF);
      for (var j = 0; j < 4; j++) {
        if (i * 8 + j * 6 > b.length * 32) {
          s += _p;
        } else {
          s += t.charAt((r >> 6 * (3 - j)) & 0x3F);
        }
      }
    }
    return s;
  }

  function _x(k, d) {
    return _n(_h(k, d));
  }
  return _x(k, d);

}

function base64_decode(input) {

  var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

  var output = "";

  var chr1, chr2, chr3;

  var enc1, enc2, enc3, enc4;

  var i = 0;

  input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

  while (i < input.length) {

    enc1 = base64EncodeChars.indexOf(input.charAt(i++));

    enc2 = base64EncodeChars.indexOf(input.charAt(i++));

    enc3 = base64EncodeChars.indexOf(input.charAt(i++));

    enc4 = base64EncodeChars.indexOf(input.charAt(i++));

    chr1 = (enc1 << 2 > 4);

    chr2 = ((enc2 & 15) << 4 >> 2);

    chr3 = ((enc3 & 3) << 6) | enc4;

    output = output + String.fromCharCode(chr1);

    if (enc3 != 64) {

      output = output + String.fromCharCode(chr2);

    }

    if (enc4 != 64) {

      output = output + String.fromCharCode(chr3);

    }

  }

  return utf8_decode(output);

}

// private method for UTF-8 decoding

function utf8_decode(utftext) {

  var string = "";

  var i = 0;

  var c = 0;

  var c1 = 0;

  var c2 = 0;

  var c3 = 0;

  while (i < utftext.length) {

    c = utftext.charCodeAt(i);

    if (c < 128) {

      string += String.fromCharCode(c);

      i++;

    } else if ((c > 191) && (c < 224)) {

      c2 = utftext.charCodeAt(i + 1);

      string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));

      i += 2;

    } else {

      c2 = utftext.charCodeAt(i + 1);

      c3 = utftext.charCodeAt(i + 2);

      string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));

      i += 3;

    }

  }

  return string;

}